#!/usr/bin/python
# -*- coding: UTF-8 -*-

"""
@author: andi
@contact: 643562684@qq.com
@time: 2022/5/27 14:40
"""

# !/usr/bin/python
# -*- coding: UTF-8 -*-

"""
@author: andi
@contact: 643562684@qq.com
@time: 2022/5/27 14:30
"""

import smtplib, os, time
from datetime import datetime
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

from common.log import logger
from common.read_Ini import Read_InI
from Conf.setting import PROJECT_CONF_SETTING


class SendMail:
    _email = Read_InI(PROJECT_CONF_SETTING['project']).data['email']

    def __init__(self, content: str = '', subject: str = ''):
        """

        :param fromaddr: 发送邮件的人
        :param password: 邮箱smtp的认证吗
        :param toaddrs: 发送个谁,list 就是多个对象
        :param content: 邮件文本内正文
        :param Subject:  文本标题
        :param smtp_type: 邮件服务类型
        """
        self.fromaddr = self._email.get("user")
        self.password = self._email.get("password")
        self.toaddrs = self._email.get("to_addrs")
        self.smtp_type = self._email.get("host")
        self._em = MIMEMultipart()
        self._em['Subject'] = subject or "测试报告"
        self._em['From'] = Header(self.fromaddr)  # 发送人
        self._em['To'] = Header(self.toaddrs)  # 收件人
        _content = content or str(datetime.now().strftime('%Y-%M-%d %H'))
        textApart = MIMEText(_content, 'plain', 'utf-8')
        self._em.attach(textApart)
        self._obj = []

    def add_image(self, image_path: str = '', img_name: str = '测试图片'):
        """添加图片"""
        suffix = self.file_exists(image_path)
        imageApart = MIMEImage(open(image_path, 'rb').read(), image_path.split('.')[-1])
        imageApart.add_header('Content-Disposition', 'attachment', filename=img_name + suffix)
        self._obj.append(imageApart)

    def add_pdf(self, pdf_path: str = '', pdf_name: str = 'pdf文件'):
        """添加pdf文件"""
        suffix = self.file_exists(pdf_path)
        pdfApart = MIMEApplication(open(pdf_path, 'rb').read())
        pdfApart.add_header('Content-Disposition', 'attachment', filename=pdf_name + suffix)
        self._obj.append(pdfApart)

    def add_zip(self, zip_path: str = '', zip_name: str = '压缩文件'):
        """添加压缩文件"""
        suffix = self.file_exists(zip_path)
        zipApart = MIMEApplication(open(zip_path, 'rb').read())
        zipApart.add_header('Content-Disposition', 'attachment', filename=zip_name + suffix)
        self._obj.append(zipApart)

    def send_email(self):
        for _ob in self._obj:
            self._em.attach(_ob)

        try:
            with smtplib.SMTP('smtp.qq.com') as server:
                server.login(self.fromaddr, self.password)
                server.sendmail(self.fromaddr, eval(self.toaddrs), self._em.as_string())
                logger.debug("邮件发送成功")
        except smtplib.SMTPException as e:
            logger.exception("邮件发送失败")
            raise e

    def file_exists(self, filename: str = ""):
        try:
            if os.path.exists(filename):
                return "." + filename.split('.')[-1]
        except FileExistsError as e:
            raise e


